<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>删除用户</title>
    <style>
        body { font-family: Arial, sans-serif; }
        .container { width: 300px; margin: 50px auto; }
        .form-group { margin-bottom: 10px; }
        label { display: block; margin-bottom: 5px; }
        input { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
        button { padding: 10px 20px; cursor: pointer; background-color: #dc3545; color: white; border: none; border-radius: 4px; }
    </style>
</head>
<body>
<div class="container">
    <h2>删除用户</h2>
    <form id="deleteUserForm">
        <div class="form-group">
            <label for="deleteUserId">用户ID:</label>
            <input type="text" id="deleteUserId" name="deleteUserId" readonly>
        </div>
        <div class="form-group">
            <label for="deleteEmail">邮箱:</label>
            <input type="email" id="deleteEmail" name="deleteEmail" readonly>
        </div>
        <div class="form-group">
            <label for="deleteContactInfo">联系方式:</label>
            <input type="text" id="deleteContactInfo" name="deleteContactInfo" readonly>
        </div>
        <div class="form-group">
            <label for="deleteAddress">地址:</label>
            <input type="text" id="deleteAddress" name="deleteAddress" readonly>
        </div>
        <div class="form-group">
            <button type="button" onclick="deleteUser()">确认删除</button>
            <button type="button" onclick="window.history.back()">取消</button>
        </div>
    </form>
</div>

<script>
    // 获取 URL 参数的函数
    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
        var results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    document.addEventListener('DOMContentLoaded', function() {
        var userId = getParameterByName('id');
        if (userId) {
            populateUserInfo(userId);
        }
    });

    // 根据用户ID填充用户信息
    function populateUserInfo(userId) {
        fetch(`/api/users/${userId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok ' + response.statusText);
                }
                return response.json();
            })
            .then(user => {
                document.getElementById('deleteUserId').value = userId;
                document.getElementById('deleteEmail').value = user.email;
                document.getElementById('deleteContactInfo').value = user.contactInfo || '';
                document.getElementById('deleteAddress').value = user.address || '';
            })
            .catch(error => {
                console.error('Error fetching user:', error);
                alert('无法加载用户信息: ' + error.message);
            });
    }

    // 删除用户
    function deleteUser() {
        var userId = document.getElementById('deleteUserId').value;

        fetch(`/api/users/${userId}`, {
            method: 'DELETE',
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                // 检查响应的内容类型，如果为空或非JSON，则不解析
                if (response.headers.get('content-type') !== 'application/json' || response.status === 204) {
                    return Promise.resolve({ success: true });
                }
                return response.json();
            })
            .then(data => {
                if (data && data.success) {
                    console.log('Success:', data);
                    alert('用户删除成功');
                    window.history.back(); // 返回上一页
                } else {
                    throw new Error('Unexpected response format');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('用户删除失败: ' + error.message);
            });
    }
</script>

</body>
</html>